package com.ls.pay.controller;

import com.ls.pay.pojo.Recharge;
import com.ls.pay.service.AlipayService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import static java.lang.System.out;

/**
 * @author 钰杰
 * @className AlipayController
 * @description VX:FengYJ996
 * @date 2020/1/314:27
 */
@Controller
public class AlipayController {

    @Autowired
    private AlipayService alipayService;


    /**
     * 支付页面跳转
     *
     * @return
     */
    @RequestMapping(value = "/toPay", method = RequestMethod.GET)
    public ModelAndView toPay(@RequestParam("appid") String appid,
                              @RequestParam("appname") String appname,
                              @RequestParam("subject") String subject,
                              ModelAndView modelAndViews) {
        out.println("跳转支付页面");
        modelAndViews.addObject("appid", appid);
        modelAndViews.addObject("appname", appname);
        modelAndViews.addObject("subject", subject);
        modelAndViews.setViewName("pay");
        return modelAndViews;
    }

    /**
     * 生成下单信息
     *
     * @param recharge
     * @return
     */
    @RequestMapping(value = "/doPay", method = RequestMethod.POST)
    public void doPay(Recharge recharge, HttpServletResponse response) {
        HttpServletResponse httpServletResponse = null;
        //生成用户与商户订单
        //防止恶意刷接口。在zuul网关增加，同一IP,同一账号，多次请求接口
        //
        alipayService.addRecharge(recharge);
        try {
            //请求支付宝接口
            httpServletResponse = alipayService.doPost(recharge, response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 支付后异步操作
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "/toNotify", method = RequestMethod.POST)
    public void toNotify(HttpServletRequest request, HttpServletResponse response) {
        try {
            String result = alipayService.toNotify(request, response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}
